#!/bin/bash

source ../../lib/shell/common.sh

function check_kernel_debug_tracing() {
    if [ -f "/sys/kernel/debug/tracing/available_tracers" ];then
        write_messages info "debugfs mounted"
        if ! cat /sys/kernel/debug/tracing/available_tracers | grep -wq hwlat;then
            write_messages warn "system do not support hwlat, skip"
            test_skip
        fi
    else
        write_messages warn "debugfs no mounted, pls check"
        test_skip
    fi

    if [ -f "/sys/kernel/tracing/hwlat_detector/width" ];then
        write_messages info "width file check exist"
    else
        write_messages warn "width file check no exist, skip"
        test_skip
    fi	

    if [ -f "/sys/kernel/tracing/hwlat_detector/window" ];then
        write_messages info "window file check exist"
    else
        write_messages warn "window file check no exist, skip"
        test_skip
    fi
}

function kernel_debug_tracing_test() {
    write_messages info "=========system hardware latency test.============="
    echo 1 > /sys/kernel/debug/tracing/tracing_thresh
    local width_val=$(cat /sys/kernel/tracing/hwlat_detector/width)
    local window_val=$(cat /sys/kernel/tracing/hwlat_detector/window)
    local thresh_val=$(cat /sys/kernel/debug/tracing/tracing_thresh)
    write_messages info "hwlat trace test, width: ${width_val}usec, window: ${window_val}usec, thresh: {$thresh_val}uesc."

    write_messages info "=========start hardware latency test.============="
    echo 1 > /sys/kernel/debug/tracing/tracing_on
    if [ "$(cat /sys/kernel/debug/tracing/tracing_on)" -ne 1 ];then
        write_messages err "hwlat trace start on failed."
        test_fail
    fi

    echo hwlat > /sys/kernel/tracing/current_tracer
    if ! cat /sys/kernel/debug/tracing/current_tracer | grep -wq hwlat;then
        write_messages err "start on hwlat trace failed, echo hwlat > current_tracer failed."
        test_fail
    fi
    wait_5_mins
    write_messages info "==================================show trace.==================================="
    cat /sys/kernel/debug/tracing/trace
    echo 0 > /sys/kernel/debug/tracing/trace
    echo 0 > /sys/kernel/debug/tracing/tracing_on
}

function wait_5_mins() {
    local count=0
    while true
    do
        sleep 10
        count=$(expr 1 + $count)
        if [ $count -ge 30 ];then
            write_messages info "wait 5 mins, time up."
            return 0
        fi
    done
}

# # # # # # # # # # # # # # main # # # # # # # # # # # # # #
check_debugfs || exit 1
check_kernel_debug_tracing
kernel_debug_tracing_test
test_pass
